/**
 * Oracle SQL生成器
 */
var generator = {
    generate: function (json) {
        var tableName = json.tableName
        var tableFields = json.tableFields

        // 组装数据列
        var tableFieldsOutput = '';
        tableFields.forEach(e => {
            var t;
            if (e.tableId) {
                t = e.field + " " + e.type + ' CONSTRAINT PK_' + tableName + ' PRIMARY KEY,\r\n'
            } else if (e.required) {
                t = e.field + " " + e.type + ' not null,\r\n'
            } else {
                t = e.field + " " + e.type + ',\r\n'
            }

            tableFieldsOutput += t
        });
        tableFieldsOutput +=
            "CREATED_BY VARCHAR2(32),\r\n" +
            "CREATED_DATE DATE,\r\n" +
            "LAST_MODIFIED_BY VARCHAR2(32),\r\n" +
            "LAST_MODIFIED_DATE DATE\r\n"
        tableFieldsOutput = tableFieldsOutput.substring(0, tableFieldsOutput.length - 2)

        // 组装列注释
        var indexTemplate = 'CREATE INDEX IDX_UK_{tableName}_{columnName} ON {tableName}({columnName});\r\n'
        var tableFieldsIndexOutput = ''
        var tableFieldsCommentOutput = ''
        tableFields.forEach(e => {
            var t = "comment on column " + tableName + '.' + e.field + ' is \'' + e.desc + "\';\r\n"
            tableFieldsCommentOutput += t
            if (e.index) {
                var t2 = indexTemplate.replace(new RegExp('{tableName}', 'ig'), json.tableName)
                t2 = t2.replace(new RegExp('{columnName}', 'ig'), e.field)
                tableFieldsIndexOutput += t2
            }
        });
        tableFieldsCommentOutput = tableFieldsIndexOutput + tableFieldsCommentOutput.substring(0, tableFieldsCommentOutput.length - 2)

        // 组装整个sql
        var createSQL = 'CREATE TABLE ' + tableName + ' (\r\n' + tableFieldsOutput + '\r\n);\r\n' + tableFieldsCommentOutput
        return createSQL.toUpperCase()
    }
}

module.exports = generator